#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include <arpa/inet.h>

#include <netinet/in.h>
#include <netinet/ip.h>

#include <sys/select.h>
#include <sys/socket.h>
#include <sys/types.h>

#include "protocol.h"

int main (int argc, char *argv[])
{
    char buf[BUFSIZE];
    fd_set wfds;
    int i, fd;
    int ret = 0;
    struct timeval timeout;
    struct sockaddr_in server_addr;

    fd = socket(AF_INET, SOCK_STREAM, 0);
    if (fd < 0)
    {
        perror("socket");
        ret = errno;
        goto e_socket;
    }

    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(SERVER_PORT);
    server_addr.sin_addr.s_addr = inet_addr(SERVER_IP);
    if (connect(fd, (struct sockaddr *) &server_addr, sizeof(server_addr)))
    {
        perror("connect");
        goto e_connect;
    }

    FD_ZERO(&wfds);

    for (i = 0; i < 10; i++)
    {
        timeout.tv_sec = 1;
        timeout.tv_usec = 0;

        FD_SET(fd, &wfds);
        ret = select(fd+1, NULL, &wfds, NULL, &timeout);
        if (ret < 0)
        {
            perror("select");
            break;
        }
        else if (ret)
        {
            snprintf(buf, BUFSIZE, "%d\n", i);
            printf("send...%s", buf);
            if (send(fd, buf, strlen(buf)+1, 0) < 0)
            {
                perror("send");
                goto e_send;
            }
        }
        else
        {
            printf("Nothing to do.\n");
        }
    }

  e_send:
  e_connect:
    close(fd);
  e_socket:

    return ret;
}

